<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="false"
			:requestApi="api.GetUserInfoListApi"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader>
				<el-button @click="openDrawer('新增')" type="primary" :icon="CirclePlus">新增用户</el-button>
				<!-- <el-button v-if="!globalStore.isPlatform" @click="batchupdatestates(scope.selectedListIds)" :icon="Edit"
					>批量设置状态</el-button
				>
				<el-button v-if="!globalStore.isPlatform" @click="batchrestPassword(scope.selectedListIds)" type="info" :icon="Refresh"
					>批量重置密码</el-button
				> -->
			</template>
			<template #states="scope">
				<el-tag :type="scope.row.states ? 'success' : 'danger'">
					{{ scope.row.states ? "启用" : "禁用" }}
				</el-tag>
			</template>
			<template #operation="scope">
				<el-space>
					<el-tag @click="openDrawer('编辑', scope.row.id)">编辑</el-tag>
					<el-tag @click="handlestates(scope.row)" :type="scope.row.states ? 'warning' : 'success'"
						>{{ scope.row.states ? "禁用" : "启用" }}
					</el-tag>
					<el-tag @click="delTable(scope.row)" type="danger">删除</el-tag>
					<el-tag @click="restPassword(scope.row)" type="info">重置密码</el-tag>
				</el-space>
			</template>
		</proTable>
		<UserDrawer ref="drawerRef" />
	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, computed, watch } from "vue";
import api from "@/api/modules/userInfo";
import roleInfoApi from "@/api/modules/roleInfo";
import { ColumnProps } from "@/components/ProTable/interface";
// import { ElMessageBox, ElMessage } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import { CirclePlus } from "@element-plus/icons-vue";
import proTable from "@/components/ProTable/index.vue";
import UserDrawer from "./components/userDrawer.vue";
import { GlobalStore } from "@/stores";
const globalStore = GlobalStore();
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	isSelectSuccess: true
});
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	if (data.data == null) {
		data.data = [];
	}
	return {
		list: data?.data,
		total: data.totalCount
	};
};
//获取角色名称信息
const getRoleNameList = async () => {
	let { result } = await roleInfoApi.GetRoleNameList({});
	if (result.code != 200) return;
	let { data } = result as any;
	data.unshift({ roleName: "全部", id: "" });
	return result;
};
//批量重置密码
// const batchrestPassword = async (ids: string[]) => {
// 	if (!ids.length) {
// 		ElMessageBox.alert("请先选择需要操作的数据！");
// 		return;
// 	}
// 	let list: any[] = ids;
// 	await useHandleData(api.ResetUserInfoPassword, { list }, "确定将所选用户登录密码重置为初始密码：a123456");
// 	proTableRef.value.clearSelection();
// 	proTableRef.value.getTableList();
// };
// //批量更改状态
// const batchupdatestates = (ids: string[]) => {
// 	if (!ids.length) {
// 		ElMessageBox.alert("请先选择需要操作的数据！");
// 		return;
// 	}
// 	ElMessageBox.confirm("请选择启用/禁用状态", "提示", {
// 		distinguishCancelAndClose: true,
// 		confirmButtonText: "启用",
// 		cancelButtonText: "禁用",
// 		center: true
// 	})
// 		.then(async () => {
// 			await api.StatusChangeUserInfo({ States: true, list: ids });
// 			ElMessage.success("批量启用成功");
// 			proTableRef.value.clearSelection();
// 			proTableRef.value.getTableList();
// 		})
// 		.catch(async () => {
// 			await api.StatusChangeUserInfo({ States: false, list: ids });
// 			ElMessage.success("批量禁用成功");
// 			proTableRef.value.clearSelection();
// 			proTableRef.value.getTableList();
// 		});
// };
//重置密码
const restPassword = async (val: any) => {
	await useHandleData(api.ResetUserInfoPassword, { List: [val.id] }, `确定将「${val.userName}」登录密码重置为初始密码：a123456`);
	proTableRef.value.clearSelection();
	proTableRef.value.getTableList();
};

//删除
const delTable = async (val: any) => {
	await useHandleData(api.DeleteUserInfo, { id: val.id }, `将「${val.userName}」的用户信息删除`);
	proTableRef.value.clearSelection();
	proTableRef.value.getTableList();
};
//禁用/启用用户状态
const handlestates = async (val: any) => {
	await useHandleData(
		api.StatusChangeUserInfo,
		{
			states: val.states ? false : true,
			list: [val.id]
		},
		`将「${val.userName}」${val.states ? "禁用" : "启用"}`
	);
	proTableRef.value.clearSelection();
	proTableRef.value.getTableList();
};
// 表格数据变化，清空批量选项
watch(
	() => proTableRef.value?.tableData,
	() => {
		proTableRef.value.clearSelection();
	}
);
// 表格配置项
let columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		// { type: "selection", width: 80, fixed: "left" },
		{ prop: "userName", label: "用户姓名" },
		{ prop: "companyName", label: "所属商户" },
		{ prop: "roleName", label: "用户角色" },
		{ prop: "userTel", label: "联系电话" },
		{ prop: "loginName", label: "登录账号" },
		{ prop: "loginTime", label: "最后登录时间" },
		{ prop: "states", label: "状态" },
		{
			prop: "roleId",
			label: "选择角色",
			enum: getRoleNameList,
			isShow: false,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "roleName", value: "id" }
		},
		{
			prop: "states",
			label: "状态",
			enum: [
				{ label: "全部", value: "" },
				{ label: "启用", value: true },
				{ label: "禁用", value: false }
			],
			isShow: false,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "label", value: "value" }
		},
		{
			prop: "LastLoginTime",
			label: "最后登录时间",
			isShow: false,
			search: { el: "date-picker", props: { filterable: true, ["value-format"]: "YYYY-MM-DD" } }
		},
		{
			prop: "userNaemOrTel",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入姓名/账户/手机号" } }
		},
		{ prop: "createUserName", label: "创建人" },
		{ prop: "createTime", label: "创建时间" },
		{ prop: "operation", label: "操作", width: 280, align: "center", fixed: "right" }
	];
	if (globalStore.isPlatform) {
		data = data.filter(i => i.prop != "companyName");
		return data;
	}
	return data;
});
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, id: string | null = null) => {
	const params = {
		title,
		isView: title === "查看",
		id,
		api: title === "新增" ? api.AddUserInfo : title === "编辑" ? api.UpdateUserInfo : undefined,
		getTableList: proTableRef.value.getTableList
	};
	drawerRef.value?.acceptParams(params);
};
</script>
